package com.module.chat;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import org.xsocket.IDestroyable;

import com.connect.agreement.IPacket;

public class ChatPacket implements IPacket,IDestroyable {

	private char mark = 0x4235;
	private char size;
	private byte channel;
	private byte[] content;
	private char end = 0x5324;
	
	private ByteBuffer buffer;
	
	public ChatPacket(int inputchannel, byte[] content) {
		this.channel = (byte)inputchannel;
		this.content = content;
		this.size = (char)(content.length&0x0000FFFF);
		buffer = ByteBuffer.allocate(content.length+7);
		buffer.position(0);
		buffer.putChar(this.mark);
		buffer.putChar(this.size);
		buffer.put(this.channel);
		buffer.put(content);
		buffer.putChar(this.end);
	}
	
	public ByteBuffer byteBuffer() {
		if (this.buffer.position() > 0) {
			this.buffer.flip();
        }
		return this.buffer;
	}
	public byte getChannel() {
		return channel;
	}
	public byte[] getContent() {
		return content;
	}
	public char getMark() {
		return mark;
	}
	public char getSize() {
		return size;
	}
	public char getEnd() {
		return end;
	}
	@Override
	public String toString() {
		try {
			return "[ChatPacket(channel:"+this.getChannel()+", size:"+this.getSize()+", content:"+new String(this.content,"UTF-8")+")]";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "[ChatPacket(channel:"+this.getChannel()+", size:"+this.getSize()+",content:"+new String(this.content)+")]";
		}
	}

	public void destroy() {
		if(this.buffer!=null)
			this.buffer.clear();
		this.buffer = null;
		this.content = null;
	}

}
